package com.leo.base_project.activity.module_Impl.socketImpl;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.leo.base_project.Utils.UIUtils;
import com.leo.base_project.databinding.ActivitySocketTestBinding;
import com.leo.base_project.module.socket.SocketService;

public class SocketTestActivity extends AppCompatActivity {

    ActivitySocketTestBinding binding;
    String ip;
    int port;
    int port2;
    SocketService client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySocketTestBinding.inflate(getLayoutInflater());
        View root = binding.getRoot();
        setContentView(root);
        client = new SocketService(handler);
    }

    public void connect(View view) {
        ip = binding.ip.getText().toString();
        port = Integer.parseInt(binding.port.getText().toString());
        client.connect(ip, port);
    }

    public void disconnect(View view) {
        if (client != null)
            client.disconnect();
    }

    public void send(View view) {
        client.send(binding.sendText.getText().toString());
        binding.sendText.setText("");
    }

    public void listen(View view) {
        if (client != null) {
            port2 = Integer.parseInt(binding.port2.getText().toString());
            client.startReceiving(port2);
            UIUtils.toast("已在端口" + port2 + "上开启监听");
        }
    }

    @SuppressLint("handlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case SocketService.CONNECTING:
                    updateState("连接中");
                    break;
                case SocketService.CONNECTED:
                    updateState("已连接");
                    break;
                case SocketService.CONNECT_ERR:
                    updateState("错误: " + msg.obj.toString());
                    break;
                case SocketService.DISCONNECTED:
                    updateState("断开连接");
                    break;
                case SocketService.RECEIVED_MSG:
                    binding.receivedText.setText("");
                    binding.receivedText.setText(msg.obj.toString());
                    break;
            }
        }
    };

    public void updateState(String text) {
        binding.state.setText(text);
    }


}